import React, { useState, useEffect, useRef } from 'react';

import { API_BASE_URL_AI } from '../utils/config';

import ConversationList from './ConversationList';

interface Message {
  content: string;
  type: 'user' | 'ai';
  timestamp: Date;
  modelId: string;
}

interface Conversation {
  _id: string;
  title: string;
  modelId: string;
  messages: Message[];
  createdAt: Date;
  updatedAt: Date;
}

// AI模型配置
const AI_MODELS = [
  {
    id: 'gpt-4',
    name: 'GPT-4',
    description: '最强大的AI模型，适合复杂任务',
    avatar: '🤖',
    color: '#10a37f',
  },
  {
    id: 'claude-3',
    name: 'Claude-3',
    description: 'Anthropic的先进AI助手',
    avatar: '🧠',
    color: '#ff6b35',
  },
  {
    id: 'qwen',
    name: '通义千问',
    description: '阿里巴巴的中文AI助手',
    avatar: '🌟',
    color: '#ff6b6b',
  },
  {
    id: 'deepseek',
    name: 'DeepSeek',
    description: '深度求索的先进AI模型',
    avatar: '🔍',
    color: '#8e44ad',
  },
];

const SmartChat: React.FC = () => {
  const [currentConversation, setCurrentConversation] =
    useState<Conversation | null>(null);
  const [showConversationList, setShowConversationList] = useState(true);
  const [inputValue, setInputValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [selectedModel, setSelectedModel] = useState(AI_MODELS[0]);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 自动滚动到底部
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [currentConversation?.messages]);

  // 创建新对话
  const createNewConversation = async () => {
    try {
      const response = await fetch(`${API_BASE_URL_AI}/conversations`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          title: '新对话',
          modelId: selectedModel.id,
        }),
      });

      const result = await response.json();
      if (result.success) {
        const newConversation = result.data;
        // setConversations(prev => [newConversation, ...prev]); // This line was removed as per the edit hint
        setCurrentConversation(newConversation);
        setShowConversationList(false);
      }
    } catch (error) {
      console.error('创建对话失败:', error);
    }
  };

  // 选择对话
  const selectConversation = (conversation: Conversation) => {
    setCurrentConversation(conversation);
    setSelectedModel(
      AI_MODELS.find(m => m.id === conversation.modelId) || AI_MODELS[0]
    );
    setShowConversationList(false);
  };

  // 发送消息
  const sendMessage = async () => {
    if (!inputValue.trim() || !currentConversation || isLoading) return;

    const userMessage: Message = {
      content: inputValue.trim(),
      type: 'user',
      timestamp: new Date(),
      modelId: selectedModel.id,
    };

    // 添加用户消息到对话
    const updatedConversation = {
      ...currentConversation,
      messages: [...currentConversation.messages, userMessage],
    };
    setCurrentConversation(updatedConversation);
    setInputValue('');
    setIsLoading(true);

    try {
      // 保存用户消息到后端
      await fetch(
        `${API_BASE_URL_AI}/conversations/${currentConversation._id}/messages`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(userMessage),
        }
      );

      // 模拟AI响应（这里可以替换为真实的API调用）
      setTimeout(
        () => {
          const aiMessage: Message = {
            content: `这是来自 ${selectedModel.name} 的回复：我理解您的问题"${userMessage.content}"，让我为您详细解答...`,
            type: 'ai',
            timestamp: new Date(),
            modelId: selectedModel.id,
          };

          const finalConversation = {
            ...updatedConversation,
            messages: [...updatedConversation.messages, aiMessage],
          };

          setCurrentConversation(finalConversation);

          // 保存AI消息到后端
          fetch(
            `${API_BASE_URL_AI}/conversations/${currentConversation._id}/messages`,
            {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify(aiMessage),
            }
          );

          setIsLoading(false);
        },
        1000 + Math.random() * 1000
      );
    } catch (error) {
      console.error('发送消息失败:', error);
      setIsLoading(false);
    }
  };

  // 处理回车键
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  // 清空当前对话
  const clearCurrentConversation = async () => {
    if (!currentConversation || !confirm('确定要清空当前对话的历史记录吗？'))
      return;

    try {
      const response = await fetch(
        `${API_BASE_URL_AI}/conversations/${currentConversation._id}/messages`,
        {
          method: 'DELETE',
        }
      );

      if (response.ok) {
        setCurrentConversation({
          ...currentConversation,
          messages: [],
        });
      }
    } catch (error) {
      console.error('清空对话失败:', error);
    }
  };

  // 删除当前对话
  const deleteCurrentConversation = async () => {
    if (!currentConversation || !confirm('确定要删除当前对话吗？')) return;

    try {
      const response = await fetch(
        `${API_BASE_URL_AI}/conversations/${currentConversation._id}`,
        {
          method: 'DELETE',
        }
      );

      if (response.ok) {
        // setConversations(prev => prev.filter(conv => conv._id !== currentConversation._id)); // This line was removed as per the edit hint
        setCurrentConversation(null);
        setShowConversationList(true);
      }
    } catch (error) {
      console.error('删除对话失败:', error);
    }
  };

  return (
    <div
      style={{
        width: '100%',
        height: '100vh',
        display: 'flex',
        backgroundColor: '#f5f5f5',
      }}
    >
      {/* 左侧对话列表 */}
      {showConversationList && (
        <div
          style={{
            width: '300px',
            height: '100%',
            borderRight: '1px solid #e9ecef',
            backgroundColor: 'white',
          }}
        >
          <ConversationList
            onSelectConversation={selectConversation}
            onCreateNew={createNewConversation}
            currentConversationId={currentConversation?._id}
          />
        </div>
      )}

      {/* 右侧聊天区域 */}
      <div
        style={{
          flex: 1,
          display: 'flex',
          flexDirection: 'column',
          height: '100%',
        }}
      >
        {/* 头部 */}
        <div
          style={{
            height: '64px',
            backgroundColor: 'white',
            borderBottom: '1px solid #e9ecef',
            display: 'flex',
            alignItems: 'center',
            padding: '0 16px',
            justifyContent: 'space-between',
          }}
        >
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '12px',
            }}
          >
            <button
              onClick={() => setShowConversationList(!showConversationList)}
              style={{
                padding: '8px',
                background: 'none',
                border: 'none',
                cursor: 'pointer',
                borderRadius: '4px',
              }}
            >
              ☰
            </button>

            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
              }}
            >
              <span style={{ fontSize: '16px' }}>{selectedModel.avatar}</span>
              <span style={{ fontSize: '16px', fontWeight: '500' }}>
                {currentConversation?.title || '新对话'}
              </span>
            </div>
          </div>

          {currentConversation && (
            <div
              style={{
                display: 'flex',
                gap: '8px',
              }}
            >
              <button
                onClick={clearCurrentConversation}
                style={{
                  padding: '6px 12px',
                  backgroundColor: '#6c757d',
                  color: 'white',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: 'pointer',
                  fontSize: '12px',
                }}
              >
                清空历史
              </button>
              <button
                onClick={deleteCurrentConversation}
                style={{
                  padding: '6px 12px',
                  backgroundColor: '#dc3545',
                  color: 'white',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: 'pointer',
                  fontSize: '12px',
                }}
              >
                删除对话
              </button>
            </div>
          )}
        </div>

        {/* 聊天消息区域 */}
        <div
          style={{
            flex: 1,
            padding: '16px',
            overflowY: 'auto',
            display: 'flex',
            flexDirection: 'column',
            gap: '16px',
          }}
        >
          {!currentConversation ? (
            <div
              style={{
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
                alignItems: 'center',
                height: '100%',
                color: '#6c757d',
                textAlign: 'center',
              }}
            >
              <div style={{ fontSize: '64px', marginBottom: '24px' }}>💬</div>
              <div style={{ fontSize: '24px', marginBottom: '16px' }}>
                欢迎使用智能对话
              </div>
              <div style={{ fontSize: '16px', marginBottom: '24px' }}>
                请从左侧选择对话或创建新对话
              </div>
              <button
                onClick={createNewConversation}
                style={{
                  padding: '12px 24px',
                  backgroundColor: '#10a37f',
                  color: 'white',
                  border: 'none',
                  borderRadius: '8px',
                  cursor: 'pointer',
                  fontSize: '16px',
                  fontWeight: '500',
                }}
              >
                开始新对话
              </button>
            </div>
          ) : (
            <>
              {currentConversation.messages.map((message, index) => (
                <div
                  key={index}
                  style={{
                    display: 'flex',
                    justifyContent:
                      message.type === 'user' ? 'flex-end' : 'flex-start',
                    marginBottom: '8px',
                  }}
                >
                  <div
                    style={{
                      maxWidth: '75%',
                      backgroundColor:
                        message.type === 'user'
                          ? selectedModel.color
                          : '#f0f0f0',
                      color: message.type === 'user' ? 'white' : '#555',
                      padding: '14px 18px',
                      borderRadius: '20px',
                      fontSize: '14px',
                      lineHeight: '1.5',
                      boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
                    }}
                  >
                    {message.content}

                    <div
                      style={{
                        fontSize: '11px',
                        color:
                          message.type === 'user'
                            ? 'rgba(255,255,255,0.7)'
                            : '#999',
                        marginTop: '6px',
                        textAlign: 'right',
                      }}
                    >
                      {new Date(message.timestamp).toLocaleTimeString('zh-CN', {
                        hour: '2-digit',
                        minute: '2-digit',
                      })}
                    </div>
                  </div>
                </div>
              ))}

              {/* 加载指示器 */}
              {isLoading && (
                <div
                  style={{
                    display: 'flex',
                    justifyContent: 'flex-start',
                    marginBottom: '8px',
                  }}
                >
                  <div
                    style={{
                      backgroundColor: '#f0f0f0',
                      padding: '14px 18px',
                      borderRadius: '20px',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '8px',
                    }}
                  >
                    <div
                      style={{
                        width: '16px',
                        height: '16px',
                        border: '2px solid #ddd',
                        borderTop: '2px solid #666',
                        borderRadius: '50%',
                        animation: 'spin 1s linear infinite',
                      }}
                    />
                    <span style={{ fontSize: '14px', color: '#666' }}>
                      {selectedModel.name} 正在思考中...
                    </span>
                  </div>
                </div>
              )}

              <div ref={messagesEndRef} />
            </>
          )}
        </div>

        {/* 底部输入框 */}
        {currentConversation && (
          <div
            style={{
              backgroundColor: 'white',
              padding: '16px',
              borderTop: '1px solid #e8e8e8',
            }}
          >
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                backgroundColor: '#f8f9fa',
                borderRadius: '24px',
                padding: '10px 18px',
                gap: '14px',
              }}
            >
              <input
                type="text"
                placeholder={`向 ${selectedModel.name} 发送消息...`}
                value={inputValue}
                onChange={e => setInputValue(e.target.value)}
                onKeyPress={handleKeyPress}
                disabled={isLoading}
                style={{
                  flex: 1,
                  border: 'none',
                  outline: 'none',
                  backgroundColor: 'transparent',
                  fontSize: '14px',
                  color: '#333',
                  padding: '4px 0',
                }}
              />

              <button
                onClick={sendMessage}
                disabled={!inputValue.trim() || isLoading}
                style={{
                  width: '36px',
                  height: '36px',
                  borderRadius: '50%',
                  backgroundColor:
                    inputValue.trim() && !isLoading
                      ? selectedModel.color
                      : '#ddd',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  cursor:
                    inputValue.trim() && !isLoading ? 'pointer' : 'not-allowed',
                  border: 'none',
                  transition: 'all 0.2s ease',
                }}
              >
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                  <path
                    d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"
                    stroke="white"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              </button>
            </div>
          </div>
        )}
      </div>

      {/* 添加CSS动画 */}
      <style>{`
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      `}</style>
    </div>
  );
};

export default SmartChat;
